package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.feign.schedule.IScheduleClient;
import com.heima.model.common.constants.ScheduleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.sound.sampled.Line;
import java.util.Date;

/**
 * @author rookie001
 * @creat 2023-06-14-21:07
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient iScheduleClient;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    //添加任务到队列中
    @Override
//    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务开始_____________");
        WmNews wmNews = new WmNews();
        wmNews.setId(id);//文章id
        Task task = Task.builder()
                .executeTime(publishTime.getTime())
                .taskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType())
                .priority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority())
                .parameters(ProtostuffUtil.serialize(wmNews))//序列化成byte[]
                .build();

        iScheduleClient.addTask(task);
        log.info("添加任务结束_____________");
    }

    //消费任务 审核文章
    @Override
    @Scheduled(fixedRate = 1000)
    public void removeNewsFromTask() {
        //获取拉取的数据
        try {
            ResponseResult poll = iScheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
//        log.info("poll {}", poll.getData().toString());
            //数据校验
            if (poll.getData() != null && poll.getCode().equals(200)) {
                log.info("消费任务-审核文章开始");
                String task = JSON.toJSONString(poll.getData());//可以强转
                Task task1 = JSON.parseObject(task, Task.class);
                byte[] parameters = task1.getParameters();
                WmNews wmnews = ProtostuffUtil.deserialize(parameters, WmNews.class);
                wmNewsAutoScanService.autoScanWmNews(wmnews.getId());
                log.info("消费任务-审核文章结束");
            }
        } catch (Exception e) {
           log.info("正在接受数据");
        }
    }
}
